﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.IO;
using ProtoType.DataStorage;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using ProtoType.ProtoTypeService;

namespace ProtoType
{
    public partial class FormsList : PhoneApplicationPage
    {
        AppSettings apps = new AppSettings();
        ProtoTypeServiceClient client;
        DataStructureStore dss = new DataStructureStore();
        ObservableCollection<Form> forms;
        DispatcherTimer timer;
        Form selectedPerson = null;
        ObservableCollection<XElement> formslist;


        public FormsList()
        {
            InitializeComponent();

            client = new ProtoTypeServiceClient();

            this.Loaded += new RoutedEventHandler(FormsList_Loaded);

            timer = new DispatcherTimer();

            timer.Tick += delegate(object s, EventArgs e)
            {
                timer.Stop();
                lbDeleteContextMenu.SelectedIndex = -1;
                DeleteContextMenu.IsOpen = true;
            };
        }
        void FormsList_Loaded(object sender, RoutedEventArgs e)
        {
            LoadForms();
        }
        private void DeleteContextMenu_Selectionchanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbDeleteContextMenu.SelectedIndex == -1)
                return;
            DeleteContextMenu.IsOpen = false;
            if (selectedPerson == null)
                return;
            forms.Remove(selectedPerson);
            selectedPerson = null;
        }
        private void lbNames_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (selectedPerson == null)
                return;
            Point position = e.GetPosition((UIElement)this);

            DeleteContextMenu.Margin = new Thickness(position.X, position.Y - 20, 20, 0);
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Start();
        }

        private void lbNames_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            timer.Stop();
            selectedPerson = MainListBox.SelectedItem as Form;
        }

        private void newButton_Click(object sender, EventArgs e)
        {
            DeleteContextMenu.IsOpen = false;
            NavigationService.Navigate(new Uri("/AddForm.xaml?flag=0", UriKind.Relative));
        }
        private void butGoToApp_Click(object sender, RoutedEventArgs e)
        {
            DeleteContextMenu.IsOpen = false;
            Button hylbutton = (System.Windows.Controls.Button)e.OriginalSource;
            (Application.Current as App).SelectedFormId = hylbutton.Tag.ToString();
            NavigationService.Navigate(new Uri("/FormData.xaml?fid=" + hylbutton.Tag, UriKind.Relative));
        }
        private void butDesign_Click(object sender, RoutedEventArgs e)
        {
            DeleteContextMenu.IsOpen = false;
            Button hylbutton = (System.Windows.Controls.Button)e.OriginalSource;
            (Application.Current as App).SelectedFormId = hylbutton.Tag.ToString();
            NavigationService.Navigate(new Uri("/Design.xaml?fid=" + hylbutton.Tag, UriKind.Relative));
            //NavigationService.Navigate(new Uri("/ManageControlList.xaml?fid=" + hylbutton.Tag, UriKind.Relative));
        }
        void LoadForms()
        {
            if (apps.IsolatedStorageSavingSetting)
            {
                BindForms(dss.LoadFormList());
            }
            if (apps.WebServiceSavingSetting)
            {
                client.LoadformListAsync();
                client.LoadformListCompleted += new EventHandler<LoadformListCompletedEventArgs>(client_LoadformListCompleted);
            }
        }

        void client_LoadformListCompleted(object sender, LoadformListCompletedEventArgs e)
        {
            formslist = new ObservableCollection<XElement>();
            formslist = e.Result.ToObservableCollection();
            BindForms(formslist);
        }

        void BindForms(ObservableCollection<XElement> formslist)
        {
            forms = new ObservableCollection<Form>();
            foreach (XElement form in formslist)
            {
                Form f = new Form();
                f.Id = int.Parse(form.Element("id").Value);
                f.Name = form.Element("name").Value;
                f.Description = form.Element("description").Value;
                forms.Add(f);
            }
            MainListBox.ItemsSource = forms;
        }

        //private void settingsButton_Click(object sender, EventArgs e)
        //{
        //    NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        //}

        private void appbar_savetocloud_Click(object sender, EventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Are you sure to replace the existing data", "MessageBoxDemo", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                dss.SaveToCloud();
            }
        }

        private void appbar_loadformcloud_Click(object sender, EventArgs e)
        {
            apps.WebServiceSavingSetting = true;
            apps.IsolatedStorageSavingSetting = false;
            LoadForms();
            //NavigationService.Navigate(new Uri("/FormsList.xaml", UriKind.Relative));
        }

        private void appbar_loadlocaldata_Click(object sender, EventArgs e)
        {
            apps.WebServiceSavingSetting = false;
            apps.IsolatedStorageSavingSetting = true;
            LoadForms();
        }
    }
}
